package com.tm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tm.constants.RedisConstans;
import com.tm.dto.ApiLogInDTO;
import com.tm.entity.UserEntity;
import com.tm.enums.StatusCodeEnum;
import com.tm.enums.StatusEnum;
import com.tm.exception.BizException;
import com.tm.service.ApiService;
import com.tm.service.UserService;
import com.tm.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author huangp
 * @create 2023-04-19 19:00
 */
@Service
@Slf4j
public class ApiServiceImpl implements ApiService {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public String ApiLogin(ApiLogInDTO apiLogInDTO) {
        //判断手机号是否存在
        JwtUtils jwtUtils = new JwtUtils();
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",apiLogInDTO.getPhone());
        UserEntity one = userService.getOne(wrapper);
        UserEntity userEntity = new UserEntity();
        if(one == null){
            //                      随机的毫秒数
            userEntity.setName("用户"+System.currentTimeMillis());
            userEntity.setPhone(apiLogInDTO.getPhone());
            userEntity.setStatus(StatusEnum.ENABLED.getCode());
            userService.save(userEntity);
        }
        String phone = apiLogInDTO.getPhone();
        String code = apiLogInDTO.getCode();
        String key = RedisConstans.getKey(phone);
        String redisCode = (String) redisTemplate.opsForValue().get(key);

        //
        if(code.equals(redisCode)){
        //生成token返回头信息
            String token = jwtUtils.createToken(userEntity);
            //将redis中验证码删除
            redisTemplate.delete(key);
            //将token放入redis中
            String token1 = RedisConstans.getToken(phone);
            redisTemplate.opsForValue().set(token1,token,RedisConstans.TOKEN_RXPIRE,RedisConstans.TIME_UNIT);
            return token;
        }
        throw new BizException(StatusCodeEnum.CODE_ERROR);

    }

}
